rm(list=ls())
library(statnet)
setwd("C:\\Documents and Settings\\Laura Metzger\\Desktop\\Dissertation\\Chapter2\\Data\\")
data<-read.csv("NC99.csv")
load("NCnet99.RData")

AMnet<-network(AM)
r<-as.vector(AM)
r<-r[r!=0]
set.edge.attribute(AMnet, "values", r, e=1:length(r))
AMnet<-network.adjacency(AM, AMnet, ignore.eval=FALSE, names.eval="values")
get.edge.attribute(AMnet$mel, "values")

same.party<-matrix(0, 126, 126)
for(i in 1:126){
for(j in 1:126){
same.party[i,j]<-ifelse(data$party[i]==data$party[j], 1, 0)
}
}

same.dist<-matrix(0, 126, 126)
for(i in 1:126){
for(j in 1:126){
same.dist[i,j]<-ifelse(data$district[i]==data$district[j], 1, 0)
}
}
same.dist<-ifelse(is.na(same.dist)==TRUE, 0, same.dist)

diag(same.dist)<-0

interact<-same.party*same.dist


mod<-ergmm(AMnet~latentcov(same.party)+latentcov(same.dist)+latent(d=2), family="Poisson", response="values", verbose=1)
mod2<-ergmm(AMnet~latent(d=2), family="Poisson", response="values", verbose=1)
dput(mod, file="results99.txt")
dput(summary(mod), file="summary99.txt")
summary(mod)

r<-predict.ergmm(mod)
f<-AM-r

pdf("DensityDifference99.pdf")
plot(density(f), main="Density of Differences between Observed and Predicted Connections", xlab="Difference in Connections")
dev.off()

pdf("DensityObsPre99.pdf")
plot(density(AM), col="red", xlim=c(-5, 20), main="Density of Observed and Predicted Connections in the NC House")
lines(density(r), col="blue", xlim=c(-5, 20))
legend(10, 0.25, c("Observed","Predicted"), col=c("red", "blue"), lty=c(1,1))
dev.off()

pdf("positions99.pdf")
plot(mod, vertex.col=data$party+1, main="MKL Latent Positions of NC House in 1997", label=TRUE, edge.col=0, what="mkl")
abline(0,0)
abline(v=0)
legend(-5, 6, c("Democrats","Republicans"), col=c("red","black"), lty=c(1,1), lwd=c(2,2))
dev.off()
